package com.boundless.helmet.ui;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.boundless.helmet.R;
import com.boundless.helmet.custom.SourceView;
import com.boundless.helmet.utils.MyFileUtils;
import com.boundless.helmet.utils.SpUtils;
import com.boundless.helmet.utils.WriteUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private AlertDialog dialog;
    private AlertDialog.Builder builder;
    private RelativeLayout rl_light;
    private RelativeLayout rl_volume;
    private ProgressBar progressbarVolume;
    private ProgressBar progressbarLight;


    private Handler handler = new Handler(Looper.myLooper());
    private SourceView sourceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }


        EventBus.getDefault().register(this);


        initView();

        initLight();

    }

    private void initView() {

        sourceView = findViewById(R.id.sourceView);

        if (sourceView != null) {
            sourceView.stopPlayResource();

            sourceView.setSourceList(MyFileUtils.getImagesAndVideosFromFolder(""));
            sourceView.startPlay();
        }

//        scheduleJob();
        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {
                    try {
                        SystemClock.sleep(1000 * 60);
                        WriteUtil.saveTimeInfo();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();

    }

    private void initLight() {
        int keyLight = SpUtils.get_key_light();
        adjustLight(keyLight);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(String message) {


        if (message == null)
            return;

//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                messageReceiver(message);
//            }
//        }, 1000);

    }


    private static final long DOUBLE_CLICK_TIME_DELTA = 300; // 双击时间间隔，单位为毫秒
    private long lastClickTime = 0;
    //    private Handler handler = new Handler();
    private Runnable runnable = () -> lastClickTime = 0;


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {


        if (event.getKeyCode() == MIDDLE_KEY || event.getKeyCode() == UP_KEY || event.getKeyCode() == DOWN_KEY) {


            if (event.getAction() == KeyEvent.ACTION_DOWN) {


                Log.d(TAG, "dispatchKeyEvent===>" + event.getKeyCode());

                switch (event.getKeyCode()) {

                    case MIDDLE_KEY:
                        //如果是中间件， 判断弹窗是否弹出，如果弹出则不做操作，如果没有弹出则弹出

                        long clickTime = System.currentTimeMillis();
                        //判断两次点击的时间差，如果小于100ms，则认为是长按， 不做操作
                        if (clickTime - lastClickTime < 100) {
                            lastClickTime = System.currentTimeMillis();
                            Log.d(TAG, "  时间小于100ms，不做操作  ");
                            return true;
                        }
                        lastClickTime = System.currentTimeMillis();


//                    long clickTime = System.currentTimeMillis();
//                    if (lastClickTime == 0) {
//                        // 第一次点击
//                        lastClickTime = clickTime;
//                        handler.postDelayed(runnable, DOUBLE_CLICK_TIME_DELTA);
//                    } else {
//                        // 可能是双击
//                        if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
//                            Log.d(TAG, "Button Double Clicked");
//                            // 执行双击操作
//                            onDoubleClick();
//                            handler.removeCallbacks(runnable);
//                            lastClickTime = 0;
//                        } else {
//                            // 不是双击，更新第一次点击时间
//                            lastClickTime = clickTime;
//                            handler.postDelayed(runnable, DOUBLE_CLICK_TIME_DELTA);
//                        }
//                    }

                        middlePress();

                        break;

                    case UP_KEY:
                        break;
                    case DOWN_KEY:
                        break;

                }

            }
            return true;

        }
        return super.dispatchKeyEvent(event);
//        return true;
    }

    private static final int MIDDLE_KEY = 26;
    private static final int UP_KEY = 24;
    private static final int DOWN_KEY = 25;

    private void onDoubleClick() {
        // 这里添加双击操作的具体代码，例如显示一个 Toast 或者执行其他操作
        Log.d(TAG, "双击事件");
    }

    //是否是调节模式
    private boolean isAdjuestMode = false;

    private void middlePress() {

        //判断弹窗是否弹出，如果弹出则不做操作，如果没有弹出则弹出
        if (dialog == null) {

            // 创建对话框构建器
            if (builder == null) {

                builder = new AlertDialog.Builder(MainActivity.this, androidx.appcompat.R.style.Theme_AppCompat_Dialog);
                // 设置自定义布局
                LayoutInflater inflater = getLayoutInflater();
                View dialogView = inflater.inflate(R.layout.layout_choose_fun, null);
//                dialogView.setLayoutParams();
                builder.setView(dialogView);

                // 创建对话框
                dialog = builder.create();

                //获取布局中的视图
                rl_light = dialogView.findViewById(R.id.rl_light);
                rl_volume = dialogView.findViewById(R.id.rl_volume);

                //声音进度条
                progressbarVolume = dialogView.findViewById(R.id.progressbarVolume);

                //亮度
                progressbarLight = dialogView.findViewById(R.id.progressbarLight);


                rl_light.setSelected(false);
                rl_volume.setSelected(false);

                dialog.setOnKeyListener((dialogInterface, keyCode, event) -> {
                    if (event.getKeyCode() == MIDDLE_KEY || event.getKeyCode() == UP_KEY || event.getKeyCode() == DOWN_KEY) {
                        if (event.getAction() == KeyEvent.ACTION_DOWN) {

                            Log.d(TAG, "====>> KeyEvent.ACTION_DOWN" + ",keyCode:" + keyCode);
                            switch (keyCode) {

                                case MIDDLE_KEY://中间键 26

                                    long clickTime = System.currentTimeMillis();
                                    //判断两次点击的时间差，如果小于100ms，则认为是长按， 不做操作
                                    Log.d(TAG, "时间差:" + (clickTime - lastClickTime));
                                    if (clickTime - lastClickTime < 550) {
                                        lastClickTime = System.currentTimeMillis();
                                        Log.d(TAG, "  时间小于550ms，不做操作  ");
                                        return true;
                                    }
                                    lastClickTime = System.currentTimeMillis();

                                    if (isNoSelect() || isAdjuestMode) {
                                        //如果都没有选中，点击后隐藏
                                        if (dialog.isShowing())
                                            dialog.dismiss();
                                    }

                                    if (rl_light.isSelected()) {
                                        //亮度
                                        Log.d(TAG, "亮度===");
                                        progressbarLight.setVisibility(View.VISIBLE);
                                        progressbarVolume.setVisibility(View.GONE);
                                        setAdjuestMode();
                                        showCurrentLight();
                                    } else if (rl_volume.isSelected()) {
                                        //音量
                                        Log.d(TAG, "音量===");
                                        progressbarLight.setVisibility(View.GONE);
                                        progressbarVolume.setVisibility(View.VISIBLE);
                                        setAdjuestMode();
                                        showCurrentVolume();
                                    } else {
                                        Log.d(TAG, "其他情况===");
                                    }

                                    break;
                                case UP_KEY://24 上下键
//                                case DOWN_KEY://25

                                    if (isAdjuestMode) {

                                        if (rl_light.isSelected()) {

                                            Log.d(TAG, " 调节亮度 ");
                                            lightPlus();
                                        } else if (rl_volume.isSelected()) {
                                            Log.d(TAG, " 调节音量 ");
                                            volumePlus();
                                        } else {

                                            Log.d(TAG, "xxx 其他情况===");
                                        }


                                    } else {

                                        if (isNoSelect()) {
                                            Log.d(TAG, "都未选===");
                                            rl_light.setSelected(true);
                                        } else if (rl_light.isSelected()) {

                                            Log.d(TAG, "选中的是亮度， 切换为音量 ");
                                            rl_light.setSelected(false);
                                            rl_volume.setSelected(true);
                                        } else if (rl_volume.isSelected()) {
                                            Log.d(TAG, "选中的是音量， 切换为亮度 ");
                                            rl_light.setSelected(true);
                                            rl_volume.setSelected(false);
                                        } else {

                                            Log.d(TAG, "其他情况===");
                                        }


                                    }


                                    break;
                                case DOWN_KEY://25


                                    if (isAdjuestMode) {

                                        if (rl_light.isSelected()) {

                                            Log.d(TAG, " 调节亮度 ");
                                            lightSub();
                                        } else if (rl_volume.isSelected()) {
                                            Log.d(TAG, " 调节音量 ");
                                            volumeSub();
                                        } else {

                                            Log.d(TAG, "xxx 其他情况===");
                                        }


                                    } else {

                                        if (isNoSelect()) {

                                            Log.d(TAG, "都未选===");
                                            rl_volume.setSelected(true);

                                        } else if (rl_light.isSelected()) {

                                            Log.d(TAG, "选中的是亮度， 切换为音量 ");
                                            rl_light.setSelected(false);
                                            rl_volume.setSelected(true);
                                        } else if (rl_volume.isSelected()) {
                                            Log.d(TAG, "选中的是音量， 切换为亮度 ");
                                            rl_light.setSelected(true);
                                            rl_volume.setSelected(false);
                                        } else {

                                            Log.d(TAG, "其他情况===");
                                        }


                                    }

                                    break;

                            }

                        }
                        return true;
                    }
                    return super.dispatchKeyEvent(event);
                });


            }

        }

        if (dialog != null && dialog.isShowing()) {
            //弹窗展示中，先判断有没有选中的条目

            if (isNoSelect()) {
                //如果都没有选中，点击后隐藏
                if (dialog.isShowing())
                    dialog.dismiss();

            } else {

                //有选中的条目，显示具体内容
                if (rl_volume.isSelected()) {
                    //显示音量调节内容
                    progressbarVolume.setVisibility(View.VISIBLE);
                    progressbarLight.setVisibility(View.GONE);
                    showCurrentVolume();
                } else if (rl_light.isSelected()) {
                    //显示亮度调节内容
                    progressbarLight.setVisibility(View.VISIBLE);
                    progressbarVolume.setVisibility(View.GONE);

                }

            }

        } else {

            // 显示对话框
            if (dialog != null) {
                dialog.show();
                resetMode();
                dialog.setOnDismissListener(dialogInterface -> {
                    //对话框消失
                    Log.d(TAG, "对话框消失");
                    resetMode();
                });
            }

            progressbarLight.setVisibility(View.GONE);
            progressbarVolume.setVisibility(View.GONE);

//            progressbar.setVisibility(View.VISIBLE);
//            progressbar.setProgress(90);
//            ll_light.setVisibility(View.VISIBLE);

        }

    }

//    /**
//     * 音量调节
//     */
//    private void volumeAdjust() {
//
//        // 获取AudioManager的实例
//        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//        if (audioManager != null) {
//            // 获取当前的音量值
//            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//            // 获取最大音量值
//            //int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//
//            int adjuestVolume = 0;
//
//            if (currentVolume >= 15) {
//                adjuestVolume = 0;
//            } else
//                adjuestVolume = currentVolume + 3;
//
//            if (adjuestVolume > 15)
//                adjuestVolume = 15;
//
//            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, adjuestVolume, AudioManager.FLAG_SHOW_UI);
//            progressbarVolume.setProgress(adjuestVolume);
//
//        }
//    }

    /**
     * 音量+
     */
    private void volumePlus() {

        // 获取AudioManager的实例
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            // 获取当前的音量值
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            // 获取最大音量值
            //int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

            if (currentVolume >= 15)
                return;

            currentVolume = currentVolume + 3;

            if (currentVolume > 15)
                currentVolume = 15;

            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_SHOW_UI);
            progressbarVolume.setProgress(currentVolume);

        }
    }

    /**
     * 音量-
     */
    private void volumeSub() {

        // 获取AudioManager的实例
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            // 获取当前的音量值
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

            if (currentVolume <= 0)
                return;

            currentVolume = currentVolume - 3;

            if (currentVolume < 0)
                currentVolume = 0;

            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_SHOW_UI);
            progressbarVolume.setProgress(currentVolume);

        }
    }

//    /**
//     * 亮度调节
//     */
//    private void lightAdjust() {
//
//        int keyLight = SpUtils.get_key_light();
//        int adjuestLight = 1;
//
//        if (keyLight >= 5) {
//            adjuestLight = 1;
//        } else
//            adjuestLight = keyLight + 1;
//
//        Log.d(TAG, "设置亮度值: " + adjuestLight);
//        SpUtils.set_key_light(adjuestLight);
//        adjustLight(adjuestLight);
//        progressbarLight.setProgress(adjuestLight);
//    }

    /**
     * 亮度+
     */
    private void lightPlus() {

        int keyLight = SpUtils.get_key_light();

        if (keyLight == 5)
            return;

        keyLight++;

        Log.d(TAG, "设置亮度值: " + keyLight);
        SpUtils.set_key_light(keyLight);
        adjustLight(keyLight);
        progressbarLight.setProgress(keyLight);
    }

    /**
     * 亮度-
     */
    private void lightSub() {

        int keyLight = SpUtils.get_key_light();


        if (keyLight == 1)
            return;

        keyLight--;

        Log.d(TAG, "设置亮度值: " + keyLight);
        SpUtils.set_key_light(keyLight);
        adjustLight(keyLight);
        progressbarLight.setProgress(keyLight);
    }

    private void resetMode() {
        isAdjuestMode = false;
    }

    private void setAdjuestMode() {
        isAdjuestMode = true;
    }

    //显示当前音量大小
    private void showCurrentVolume() {

        // 获取AudioManager的实例
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            // 获取当前的音量值
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            // 获取最大音量值
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            // 打印当前音量和最大音量
            Log.d(TAG, "当前音量值 volume: " + currentVolume + ",最大音量值:" + maxVolume);
            progressbarVolume.setMax(maxVolume);
            progressbarVolume.setProgress(currentVolume);

        }
    }

    //显示当前音量大小
    private void showCurrentLight() {
        int keyLight = SpUtils.get_key_light();
        progressbarLight.setMax(5);
        progressbarLight.setProgress(keyLight);
    }


    //是否都没有选中
    private boolean isNoSelect() {

        boolean lightSelected = rl_light.isSelected();
        boolean volumeSelected = rl_volume.isSelected();
        return !lightSelected && !volumeSelected;
    }


    private void adjustLight(int lightLevel) {

        FileOutputStream fos;

        File file = new File("/sys/class/panel-simple/brightness");

        try {
            fos = new FileOutputStream(file);
            fos.write(String.valueOf(lightLevel).getBytes("UTF-8"));
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onResume() {
        super.onResume();

        if (sourceView != null)
            sourceView.onPlayerViewResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (sourceView != null)
            sourceView.onPlayerViewPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        EventBus.getDefault().unregister(this);

        if (sourceView != null)
            sourceView.releaseExoPlayer();
    }
}